package cn.tiger.repository;

import cn.tiger.pojo.domain.Membership;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 会员数据访问层
 */
@Repository
public interface MembershipRepository extends JpaRepository<Membership, Long> {
    
    /**
     * 根据用户ID查询当前有效的会员信息
     * @param userId 用户ID
     * @param now 当前时间
     * @return 会员信息
     */
    @Query("SELECT m FROM Membership m WHERE m.userId = :userId AND m.status = 1 " +
           "AND (m.expireTime IS NULL OR m.expireTime > :now) " +
           "ORDER BY m.createTime DESC LIMIT 1")
    Optional<Membership> findCurrentMembershipByUserId(@Param("userId") Long userId, @Param("now") LocalDateTime now);
    
    /**
     * 根据用户ID查询所有会员记录
     * @param userId 用户ID
     * @return 会员记录列表
     */
    List<Membership> findByUserIdOrderByCreateTimeDesc(Long userId);
    
    /**
     * 根据用户ID和会员类型查询最新记录
     * @param userId 用户ID
     * @param membershipType 会员类型
     * @return 会员记录
     */
    Optional<Membership> findTopByUserIdAndMembershipTypeOrderByCreateTimeDesc(Long userId, String membershipType);
    
    /**
     * 查询即将过期的会员（7天内过期）
     * @param now 当前时间
     * @param sevenDaysLater 7天后时间
     * @return 即将过期的会员列表
     */
    @Query("SELECT m FROM Membership m WHERE m.status = 1 AND m.membershipType = 'VIP' " +
           "AND m.expireTime BETWEEN :now AND :sevenDaysLater")
    List<Membership> findExpiringMemberships(@Param("now") LocalDateTime now, 
                                           @Param("sevenDaysLater") LocalDateTime sevenDaysLater);
}